package com.txh.blog.controller.admin;

import com.github.pagehelper.PageInfo;
import com.txh.blog.bean.Type;
import com.txh.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class TypeController{

    @Autowired
    TypeService typeService;

    @RequestMapping("/types")
    public ModelAndView type(@RequestParam(name = "page",required = true,defaultValue = "1") int page, @RequestParam(name = "pageSize",required = true,defaultValue = "4")int pageSize){
        List<Type> all = typeService.findAll(page, pageSize);
        PageInfo<Type> info=new PageInfo<>(all);
        ModelAndView mv=new ModelAndView();
        mv.addObject("pageInfo",info);
        mv.setViewName("admin/types");
        return mv;
    }
    @RequestMapping("/save")
    @ResponseBody
    public String save(Type type){
        Type name = typeService.findByName(type.getName());
        if(name!=null){
            return "1";
        }
        typeService.save(type);
        return "0";
    }
    @RequestMapping("/delete")
    public String delete(@RequestParam Long id){
        typeService.delete(id);
        return "redirect:/admin/types";
    }
    @RequestMapping("/findById")
    public ModelAndView findById(@RequestParam Long id){
        Type type = typeService.findById(id);
        ModelAndView mv=new ModelAndView();
        mv.addObject("type",type);
        mv.setViewName("admin/types-input");
        return mv;
    }
    @RequestMapping("/update")
    public String update(Type type){
        typeService.update(type);
        return "redirect:/admin/types";
    }
}
